<template>
  <div class="time-select">
    <!-- 添加排班 -->
    <table ref="table" style="width:100%">
      <tr>
        <th rowspan="2" class="label">时间</th>
        <th colspan="24">00:00 - 12:00</th>
        <th colspan="24">12:00 - 24:00</th>
      </tr>
      <tr>
        <td v-for="(item, index) in 24" :key="index" colspan="2">{{ index }}</td>
      </tr>
      <tr>
        <td class="label"></td>
        <td v-for="(item, index) in timeBlockList" :key="index" class="time-block"
          :style='{ backgroundColor: item.color }' @click="changeTime(item, index)" @mouseover="showTimeTip(index)"
          @mouseout="disTimeTip">
          <span class="time-tip" v-if="index == currentIndex">{{ item.formatTime }}</span>
        </td>
      </tr>
    </table>
    <!-- 管理排班 -->
    <el-table :data="formatTimeList" style="width: 100%;margin-top: 50px;" stripe v-if="seqBlock.length > 0"
      :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
      <el-table-column label="排班时间" sortable :sort-method="sortByDate">
        <template #default="scope">
          <div style="display: flex; align-items: center; justify-content: center;">
            <el-icon>
              <timer />
            </el-icon>
            <span style="margin-left: 10px">{{ scope.row.formatTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="电影名称">
        <template #default="scope">
          <el-tag type="success">{{ scope.row.movieName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="电影时长">
        <template #default="scope">
          <el-tag v-if="scope.row.color == '#ff0000'">{{ scope.row.movieDuring }}分钟</el-tag>
          <el-tag v-if="scope.row.color == '#0000ff'">{{ scope.row.movieDuring }}分钟</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="影厅名称">
        <template #default="scope">
          {{ scope.row.roomName }}
        </template>
      </el-table-column>
      <el-table-column label="影厅类型">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.roomType == 1">小</el-tag>
          <el-tag type="warning" v-if="scope.row.roomType == 2">中</el-tag>
          <el-tag type="success" v-if="scope.row.roomType == 3">大</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" :filters="[
        { text: '已排班', value: '#ff0000' },
        { text: '未排班', value: '#0000ff' },
      ]" :filter-method="filterTag" filter-placement="bottom-end">
        <template #default="scope">
          <el-tag v-if="scope.row.color == '#ff0000'" type="danger">已排班</el-tag>
          <el-tag v-if="scope.row.color == '#0000ff'" type="success">未排班</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)"
            v-if="scope.row.color == '#ff0000'">删除排班</el-button>
          <el-button size="small" @click="handleConfirm(scope.$index, scope.row)" v-if="scope.row.color == '#0000ff'"
            type="warning">确认排班</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <div v-for="(item,index) in formatTimeList" :key="index">{{item}}</div> -->
  </div>
</template>

<script lang="ts" setup>
import { computed } from '@vue/reactivity';
import { ElMessage } from 'element-plus';
import { onMounted, ref, watch, defineEmits } from 'vue'
import { delScheduleById, addSchedule } from '../../../../../api/schedule'
import { deepClone } from '../../../../../utils/index'

const emits = defineEmits(['getScheduleByDate'])

interface ITimeBlock {
  scheduleId?: number
  movieDuring: number
  movieName: string
  start: number
  end: number
  isChoose: boolean
  color: string
  formatTime?: string

  roomName?: string,
  roomType?: number,
}

interface IHotMovie {
  movieCover: string
  movieDesc: string
  movieId: number
  movieName: string
  movieScore: number
  movieScoreNum: number
  movieTypeId: number
  movieView: number
  movieDuring: number
}

interface IRoom {
  roomId: number
  cinemaId: number
  roomName: string
  roomContain: number
  roomType: number
  roomRow: number
  roomCol: number
  roomOpen: number
  createTime: string
}


let timeBlockList = ref<ITimeBlock[]>([])
let seqBlock = ref<ITimeBlock[]>([])
let currentIndex = ref(-1)
const userId = JSON.parse(window.sessionStorage.getItem("currentUser")!).userId


const sortByDate = (row: ITimeBlock, row1: ITimeBlock) => {
  if (row.start > row1.start) {
    return -1
  } else {
    return 1
  }
}

const handleConfirm = (index: number, row: ITimeBlock) => {
  // console.log(row.start / 30, row.end / 30, props.movieInfo?.movieId, props.movieInfo?.movieId, props.current, userId)
  // debugger
  if (row.end - row.start < props.movieInfo!.movieDuring) {
    ElMessage.error("时长分配不足，请重新分配")
    return
  }
  if (row.end - row.start - props.movieInfo!.movieDuring >= 30) {
    ElMessage.error("时长分配过长，请重新分配")
    return
  }

  addSchedule(
    {
      date: props.current,
      start: row.start,
      end: row.end,
      cinemaId: JSON.parse(window.sessionStorage.getItem("currentUser")!).unitId,
      movieId: props.movieInfo?.movieId,
      roomId: props.roomInfo?.roomId,
      userId: userId
    }
  ).then((res: any) => {
    debugger
    if (res.code == 200) {
      // row.color = '#ff0000'
      let start = row.start / 30
      let end = row.end / 30
      for (let i = start; i < end; i++) {
        timeBlockList.value[i].color = '#ff0000'
        debugger
        timeBlockList.value[i].scheduleId = res.data.scheduleId
      }
      debugger
      let seq = seqBlock.value.find((item: ITimeBlock) => {
        return item.start == row.start && item.end == row.end
      })
      seq!.color = '#ff0000'
      seq!.scheduleId = res.data.scheduleId
    } else {
      ElMessage.error("排班添加失败")
    }
  })


}
const handleDelete = async (index: number, row: ITimeBlock) => {
  await delScheduleById({ scheduleId: row.scheduleId }).then((res: any) => {
    if (res.code == 200) {
      let start = row.start / 30
      let end = row.end / 30
      for (let i = start; i < end; i++) {
        timeBlockList.value[i].color = ''
      }
      seqBlock.value.splice(index, 1)
      ElMessage.success("排班删除成功")
    } else if (res.code == 500) {
      ElMessage.error(res.msg)
    }
    else {
      ElMessage.error("排班删除失败")
    }
  })
  emits("getScheduleByDate")
}

const filterTag = (value: string, row: ITimeBlock) => {
  return row.color === value
}

const props = defineProps<{
  list: ITimeBlock[],
  roomInfo: IRoom | undefined | null,
  movieInfo: IHotMovie | undefined | null,
  current: string
}>()

const formatTimeList = computed(() => {
  debugger
  return seqBlock.value.map((item: ITimeBlock) => {
    return {
      ...item,
      formatTime: `${Math.floor(item.start / 30 / 2).toString().padStart(2, '0')}:${((item.start / 30 % 2) * 30).toString().padStart(2, '0')} - ${Math.floor(item.end / 30 / 2).toString().padStart(2, '0')}:${((item.end / 30 % 2) * 30).toString().padStart(2, '0')}`
    }
  });
})


watch(
  () => props.list,
  (n, o) => {
    initTimeBlock()
    for (let i = 0; i < props.list.length; i++) {
      debugger
      seqBlock.value.push(props.list[i])
      let start = props.list[i].start / 30
      let end = props.list[i].end / 30
      for (let j = start; j < end; j++) {
        timeBlockList.value[j].isChoose = true
        timeBlockList.value[j].movieName = props.list[i].movieName
        timeBlockList.value[j].color = '#ff0000'
      }
    }
  },
  { deep: true }
)

const initTimeBlock = () => {
  timeBlockList.value = []
  seqBlock.value = []
  for (let i = 0; i < 48; i++) {
    let startTime = i * 30
    const obj: ITimeBlock = {
      movieDuring: 0,
      movieName: '',
      start: startTime,
      end: startTime + 30,
      isChoose: false,
      color: '',
      formatTime: ''
    }
    obj.formatTime = `${Math.floor(obj.start / 30 / 2).toString().padStart(2, '0')}:${((obj.start / 30 % 2) * 30).toString().padStart(2, '0')} - ${Math.floor(obj.end / 30 / 2).toString().padStart(2, '0')}:${((obj.end / 30 % 2) * 30).toString().padStart(2, '0')}`
    timeBlockList.value?.push(obj)
  }
}
const showTimeTip = (index: number) => {
  currentIndex.value = index
}
const disTimeTip = () => {
  currentIndex.value = -1
}

onMounted(() => {
  initTimeBlock()
})

const changeTime = (item: ITimeBlock, index: number) => {
  // debugger
  if (props.roomInfo == undefined) {
    ElMessage.error("请先选择影厅")
    return
  }
  if (props.movieInfo == undefined) {
    ElMessage.error("请先选择电影")
    return
  }
  // 判断取消的是不是已选电影
  if (item.color == '#ff0000') {
    ElMessage.error("不能修改已排电影，请删除后重新添加")
    return
  }
  // 判断左右两边是否是已排时间段
  debugger
  if (index == 0) {
    if (timeBlockList.value[index + 1].color == '#ff0000') {
      ElMessage.error("两场电影之间必须间隔30分钟")
      return
    }
  } else if (index == timeBlockList.value.length - 1) {
    if (timeBlockList.value[index - 1].color == '#ff0000') {
      ElMessage.error("两场电影之间必须间隔30分钟")
      return
    }
  } else {
    if (timeBlockList.value[index - 1].isChoose && timeBlockList.value[index + 1].isChoose) {
      ElMessage.error("两场电影之间必须间隔30分钟")
      return
    }
    if (timeBlockList.value[index - 1].color == '#ff0000' || timeBlockList.value[index + 1].color == '#ff0000') {
      ElMessage.error("不能修改已排电影")
      return
    }
  }

  // debugger
  // ishave 表示能否与已有选区合并
  let isHave: boolean = false
  if (item.isChoose == true) {
    // 如果是取消该方块，不能从中间取消
    for (let i = 0; i < seqBlock.value.length; i++) {
      let it = seqBlock.value[i]
      // 如果取消的方块在前面
      if (it.start == item.start) {
        it.start = item.end
        isHave = true
        // 取消掉那唯一一个的情况
        if (it.start >= it.end) {
          const findIndex = seqBlock.value.findIndex(thing => {
            return thing.start == item.end
          })
          seqBlock.value.splice(findIndex, 1)
        }
      } else if (it.end == item.end) {
        // 如果取消的方块在后头
        it.end = item.start
        isHave = true
        // 取消掉那唯一一个的情况
        if (it.start >= it.end) {
          const findIndex = seqBlock.value.findIndex(thing => {
            return thing.start == item.start
          })
          seqBlock.value.splice(findIndex, 1)
        }
      }
      // 如果是加在中间的
      if (item.start > it.start && item.start < it.end) {
        ElMessage.error('不能从中间取消时间')
        return
      }
    }
    item.isChoose = false
    item.color = ''
    // if (!isHave) { 
    //   debugger 
    //   seqBlock.value.push(deepClone(item)) 
    // }
  } else {
    let cnt = 0
    // 用于判断是否从中间加的情况
    // 如果是加上该方块
    for (let i = 0; i < seqBlock.value.length; i++) {
      let it = seqBlock.value[i]
      if (it.start == item.end) {
        //如果该方块是加在前头
        // cnt++
        // if (cnt < 2) {
        it.start = item.start
        isHave = true
        // } else {
        //   seqBlock.value[i - 1].end -= 30
        //   ElMessage.error("两场电影之间必须间隔30分钟")
        //   return
        // }
      } else if (it.end == item.start) {
        //如果该方块是加在后头
        // cnt++
        it.end = item.end
        isHave = true
      }
    }
    item.isChoose = true
    item.color = '#0000ff'
    item.movieName = props.movieInfo.movieName
    item.movieDuring = props.movieInfo.movieDuring
    item.roomName = props.roomInfo.roomName
    item.roomType = props.roomInfo.roomType
    if (!isHave) seqBlock.value.push(deepClone(item))
  }
}
</script>


<style lang="less" scoped>
.time-select {
  display: inline-block;
  width: 100%;

  table {
    font-family: PingFangSC-Regular, tahoma, arial, 'Hiragino Sans GB',
      'Microsoft yahei', sans-serif;
    text-align: center;
    border-collapse: collapse;
    font-size: 12px;
    color: #333333;
    user-select: none;

    th,
    td {
      border: 1px solid #dee4f5;
      line-height: 1.8em;
    }

    .label {
      padding: 0 5px;
    }

    .time-block {
      position: relative;
      width: 26px;
      height: 22px;
      background: #f5f5f5;

      .time-tip {
        position: absolute;
        top: 30px;
        border-radius: 10px;
        left: -60px;
        width: 100px;
        display: inline-block;
        color: white;
        background-color: rgba(0, 0, 0, 0.6);
      }

      &.active {
        background: #0000ff;
      }
    }
  }
}
</style>